import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  Keyboard,
  Modal,
  FlatList,
  RefreshControl,
  ActivityIndicator,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {TextButton, LinearButton} from '../../components/Button';
import {NormalHeader} from '../../components/NavigationHeader';
import {showToast} from '../../components/Toast';
import {userLogout} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import UserPriceCell from './components/UserPriceCell';
import {queryUserOffers} from '../../api/auction';
import {BASE_API} from '../../config';
import moment from 'moment';
import LinearGradient from 'react-native-linear-gradient';
import {subNumerString} from '../../utils/tools';
import ChainUtils from '../../utils/chain/ChainUtils';
import BigNumber from 'bignumber.js';

//#FFCB26

const styles = StyleSheet.create({
  selectBar: {
    backgroundColor: '#2B085E',
    marginLeft: 20,
    marginRight: 20,
    marginTop: 10,
    flexDirection: 'row',
    height: 50,
    borderRadius: 25,
    alignItems: 'center',
  },
  optionButton: {
    height: 35,
    flex: 1,
    marginLeft: 10,
    marginRight: 10,
    marginTop: 0,
  },
});
class Auction extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      currentType: 0,
      isRefreshing: false,
      prices: [],
      page: 1,
      size: 10,
      total: 0,
    };
  }

  formatPrice = (price, payCoinDecimal) => {
    price = new BigNumber(price);
    const decimal = new BigNumber(Math.pow(10, payCoinDecimal));
    let vAmount = parseFloat(price.dividedBy(decimal));
    let s = ChainUtils.subStringNum(vAmount, 4);
    return s;
  };

  loadMore = () => {
    if (this.state.total >= this.state.page * this.state.size) {
      this.setState(
        {
          page: this.state.page + 1,
        },
        () => {
          this.getList();
        },
      );
    }
  };

  getList = async () => {
    let {page, size, currentType} = this.state;
    queryUserOffers({
      address: this.props.userInfo.metamaskAddress,
      page,
      size,
      type: currentType,
    })
      .then((res) => {
        var newPrices = res.data.rows.map((item) => {
          console.log(item.value);
          return {
            ...item,
            value: this.formatPrice(item.value, item.payCoinDecimal),
            userImg: BASE_API + item.userImg,
            time: moment(item.creteTime).format('YYYY-MM-DD hh:mm:ss'),
          };
        });

        if (page !== 1) {
          newPrices = this.state.prices.concat(newPrices);
        }

        console.log(newPrices);

        this.setState({
          prices: newPrices,
          total: res.data.pageInfo.total,
        });
      })
      .catch((err) => {
        console.log(err);
        showToast(err.msg || 'falied');
      });
  };
  componentDidMount() {
    this.onRefresh();
  }

  onRefresh = async () => {
    this.setState({
      isRefreshing: true,
      page: 1,
    });

    await this.getList();

    this.setState({
      isRefreshing: false,
    });
  };

  enterAuction = (item) => {
    console.log(item);

    this.props.navigation.navigate('Auction', {
      auction: {auctionId: item.auctionId},
    });
  };

  _renderEmptyView = () => (
    <View
      style={{
        //   backgroundColor: 'yellow',
        width: '100%',
        height: 300,
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <Image
        style={{width: 95}}
        source={require('../../assets/browser/empty.png')}></Image>
      <Text style={{color: 'white', padding: 20, alignSelf: 'center'}}>
        No offers yet
      </Text>
    </View>
  );

  _renderItemSeparatorComponent = () => (
    <View style={{height: 10, backgroundColor: 'transparent'}} />
  );

  _renderItem = (item) => (
    <LinearGradient
      start={{x: 0, y: 1}}
      end={{x: 1, y: 1}}
      colors={['#CE18EC', '#6601F5']}
      style={{flex: 1, borderRadius: 10, padding: 2}}>
      <View style={{backgroundColor: '#2B085E', borderRadius: 10}}>
        <UserPriceCell
          price={item.item}
          textColor={'white'}
          swapSymbol={this.props.swapSymbol}
          onPress={() => this.enterAuction(item.item)}
        />
      </View>
    </LinearGradient>
  );

  auctionListFooterComponent = () => {
    let showLoadingMore = this.state.total >= this.state.page * this.state.size;

    return this.state.prices.length == 0 ? null : (
      <View>
        <View
          style={{
            flexDirection: 'row',
            color: 'white',
            justifyContent: 'center',
          }}>
          {showLoadingMore ? (
            <ActivityIndicator size="small" animating={true} />
          ) : null}
          <Text style={{color: 'white', marginLeft: 10}}>
            {showLoadingMore ? 'loading more...' : ''}
          </Text>
        </View>
      </View>
    );
  };

  renderComponent = () => {
    let gasCoin = this.props.coins.filter((item) => {
      return item.symbol == this.props.gasSymbol;
    })[0];
    let proportion = gasCoin.price;

    let {currentType, prices} = this.state;

    let newPrices = prices.map((item, idx) => {
      return {
        ...item,
      };
    });
    return (
      <View style={{flex: 1, backgroundColor: '#160231'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Offers"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <View style={styles.selectBar}>
          {currentType == 0 ? (
            <LinearButton
              text={'Offers Made'}
              buttonStyle={styles.optionButton}
              textStyle={{color: 'white'}}
              onPress={() => {
                this.setState({currentType: 0, page: 1}, () => {
                  this.onRefresh();
                });
              }}
            />
          ) : (
            <TextButton
              text={'Offers Made'}
              textStyle={{color: 'white'}}
              buttonStyle={[
                styles.optionButton,
                {backgroundColor: 'transport'},
              ]}
              onPress={() => {
                this.setState({currentType: 0}, () => {
                  this.onRefresh();
                });
              }}
            />
          )}
          {currentType == 1 ? (
            <LinearButton
              text={'Offers Received'}
              buttonStyle={[styles.optionButton, {marginLeft: 0}]}
              textStyle={{color: 'white'}}
              onPress={() => {
                this.setState({currentType: 1, page: 1}, () => {
                  this.onRefresh();
                });
              }}
            />
          ) : (
            <TextButton
              text={'Offers Received'}
              textStyle={{color: 'white'}}
              buttonStyle={[
                styles.optionButton,
                {backgroundColor: 'transport', marginLeft: 0},
              ]}
              onPress={() => {
                this.setState({currentType: 1}, () => {
                  this.onRefresh();
                });
              }}
            />
          )}
        </View>
        <View style={{padding: 20, flex: 1}}>
          <FlatList
            style={{marginTop: 0}}
            data={newPrices}
            keyExtractor={(item, index) => item.price} // 给定的item生成一个不重复的key
            renderItem={this._renderItem}
            ListEmptyComponent={this._renderEmptyView}
            ItemSeparatorComponent={this._renderItemSeparatorComponent}
            refreshControl={
              <RefreshControl
                tintColor="white"
                refreshing={this.state.isRefreshing}
                onRefresh={this.onRefresh}
                colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
                progressBackgroundColor="#ffffff"
              />
            }
            ListFooterComponent={this.auctionListFooterComponent}
            onEndReached={this.loadMore}
            onEndReachedThreshold={0.2}
          />
        </View>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  coins: state.Chain.coins,
  gasSymbol: state.Chain.gasSymbol,
  swapSymbol: state.Chain.swapSymbol,
});

const mapDispatchToProps = (dispatch) => ({
  userLogout: (item) => dispatch(userLogout()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Auction);
